<template>
  <div id="tdtMapDivID" style="width: 100%; height: 100%;padding-top: 24px"></div>
  <!-- <img src="./mapimg/green.png" alt=""> -->
</template>

<script>
import useView from "@/hooks/useView";
import {defineComponent, reactive, toRefs} from "vue";
import baseService from "@/service/baseService";

export default defineComponent({
  name: "MapDiv",
  setup() {
    const state = reactive({
      map: null,
      mapdata: [],
      TMaplnglats: [],
      mapLngLat: {},
      markreData: null
    });
    return {...useView(state), ...toRefs(state)};
  },
  mounted() {
    this.getMapData();
  },
  methods: {
    // 地图数据
    getMapData() {
      baseService.get("/KxStation/kxstation/getMapList").then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        }
        this.mapdata = res.data;
        this.mapdata.forEach((row) => {
          this.mapLngLat[row.id] = {lat: row.lat, lng: row.lng};
        });
        // console.log(this.mapLngLat);
        this.initMap(103.388611, 35.563611, 4);
      });
    },
    /**
     * 初始化地图
     * @param {*} lng 经度
     * @param {*} lat 纬度
     * @param {*} zoom 缩放比例(1~18)
     **/
    initMap(lng, lat, zoom) {
      let T = window.T;
      //地图实例
      this.map = new T.Map("tdtMapDivID");
      // this.map.centerAndZoom(new T.LngLat(lng, lat), zoom);
      // 去掉水印
      document.getElementsByClassName("tdt-control-copyright tdt-control")[0].style.display = "none";
      //创建卫星和路网的混合视图
      this.map.setMapType(window.TMAP_HYBRID_MAP);
      // 加载点位图标
      if (this.mapdata != null && this.mapdata.length > 0) {
        let maxl = this.mapdata[0].lng,
            minl = this.mapdata[0].lng,
            maxb = this.mapdata[0].lat,
            minb = this.mapdata[0].lat;
        for (var i = 0; i < this.mapdata.length; i++) {
          this.TMaplnglats.push(new T.LngLat(this.mapdata[i].lng, this.mapdata[i].lat));
          this.addMarker(this.mapdata[i], T, false);

          if (this.mapdata[i].lng === null || this.mapdata[i].lat === null) {
            continue;
          }

          if (this.mapdata[i].lng > maxl) maxl = this.mapdata[i].lng;
          if (this.mapdata[i].lng < minl) minl = this.mapdata[i].lng;
          if (this.mapdata[i].lat > maxb) maxb = this.mapdata[i].lat;
          if (this.mapdata[i].lat < minb) minb = this.mapdata[i].lat;
        }

        let cenLng = (parseFloat(maxl) + parseFloat(minl)) / 2;
        let cenLat = (parseFloat(maxb) + parseFloat(minb)) / 2;
        let zoom = this.getZoom(maxl, minl, maxb, minb);
        this.map.centerAndZoom(new T.LngLat(cenLng, cenLat), zoom);
      } else {
        //没有坐标，显示全中国
        this.map.centerAndZoom(new T.LngLat(103.388611, 35.563611), 5);
      }
    },
    // 计算地图缩放比例
    getZoom(maxLng, minLng, maxLat, minLat) {
      var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。
      var pointA = new T.LngLat(maxLng, maxLat);  // 创建点坐标A
      var pointB = new T.LngLat(minLng, minLat);  // 创建点坐标B
      var distance = this.map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位
      for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
        if (zoom[i] - distance > 0) {
          return 18 - i + 3;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
        }
      }
    },
    // 查找id对应信息
    findMarsk(id) {
      for (let item of this.mapdata) {
        if (item.id === id) {
          this.markreData = item
          break;
        }
      }
      if (this.markreData.lng != null && this.markreData.lat != null) {
        this.marsktu(this.markreData.lng, this.markreData.lat)
      } else {
        this.$message.warning("该杆塔暂无坐标信息！");
      }
    },
    // 点位寻找
    marsktu(lng, lat) {
      let T = window.T;
      // this.map.clearOverLays();
      this.map.centerAndZoom(new T.LngLat(lng, lat), 100);
      // 定义该矩形的显示区域
      let circle = new T.Circle(new T.LngLat(lng, lat), 40, {
        color: "red",
        weight: 3,
        opacity: 0.5,
        fillColor: "#FFFFFF",
        fillOpacity: 0.1,
        lineStyle: "solid"
      });
      //向地图上添加圆
      // this.map.addOverLay(circle);
    },
    addMarker(markdata, T, flag) {
      let marker;
      let icon;
      let point;
      let url0 = "/mapimg/inf.png"; //离线
      let url1 = "/mapimg/green.png"; //在线
      let url2 = "/mapimg/red.png"; //报警
      if (markdata.status === "offline") {
        // 离线
        icon = new T.Icon({
          iconUrl: url0,
          // TIcon(iconurl0, new TSize(35, 50), {anchor: new TPixel(20, 50)});
          // iconSize: new T.Point(22, 40),
          // iconAnchor: new T.Point(10, 25)
          iconSize: new T.Point(50, 50),
          iconAnchor: new T.Point(15, 52)
        });
        point = new T.LngLat(markdata.lng, markdata.lat);
        marker = new T.Marker(point, {icon: icon}); // 创建标注
      } else if (markdata.status === "normal") {
        //正常
        icon = new T.Icon({
          iconUrl: url1,
          iconSize: new T.Point(50, 50),
          iconAnchor: new T.Point(15, 52)
        });
        point = new T.LngLat(markdata.lng, markdata.lat);
        marker = new T.Marker(point, {icon: icon}); // 创建标注
      } else {
        //报警
        icon = new T.Icon({
          iconUrl: url2,
          iconSize: new T.Point(50, 50),
          iconAnchor: new T.Point(15, 52)
        });

        point = new T.LngLat(markdata.lng, markdata.lat);
        marker = new T.Marker(point, {icon: icon}); // 创建标注
      }
      this.map.addOverLay(marker); // 将标注添加到地图中
      var deviceInfo = "";
      var parentCode = "";
      for (var i = 0; i < markdata.length; i++) {
        var deviceStatus = "<i style='display:inline-block; background-color: #dc1212;width:8px;height:8px;border-radius:50%;' ></i> ";
        if (null != markdata[i].enable && markdata[i].enable.indexOf("t") != -1) {
          deviceStatus = "<i style='display:inline-block; background-color: #12cc31;width:8px;height:8px;border-radius:50%;' ></i> ";
        }
        deviceInfo += `<p style="color: #999; margin: 0px;">${deviceStatus}${markdata[i].name}</p>`;
        parentCode = markdata[0].serialNo;
      }
      var wy = "";
      if (markdata.track > 1) {
        wy = '<span style="width: 80px;display: inline-block;"></span><a href="javascript:centerMarker(\'' + markdata.id + "')\">位移轨迹<a>";
      }

      let content = ` <div class="xxdiv">
        <p style="font-size: 16px; text-align:center;color: #fff; font-weight:bold; margin: 0px; margin-bottom: 10px">${markdata.name}</p>
        <p style="font-size: 14px; color: #fff; margin: 0px;">所属组织：${markdata.deptName}${wy}</p>
        <p style="color: #fff; margin: 4px 0px 4px 0px;">
          <span style="color: #fff;">经度：${markdata.lng}</span>
          <span style="color:#fff; margin-left: 10px;"> 纬度：${markdata.lat}</span>
        </p>
        <p style="color: #fff;font-size: 14px; margin: 0px;">设备信息：</p>${deviceInfo}
        <span style='display:none'>${parentCode}</span>
        <p style="font-size: 14px; color: #fff; margin: 0px;">${markdata.addr ? markdata.addr : ""}</p>
<!--        <p>-->
<!--          <button onclick=videoFlg('Emd.Device.Camera.E0')>球机</button>-->
<!--          &nbsp;&nbsp;&nbsp;-->
<!--          <button onclick=videoFlg('Emd.Device.Camera.E1')>枪机</button>-->
<!--        </p>-->
      </div>`;
      if (flag) {
        this.map.centerAndZoom(point, 5);
        let markerInfoWin = new T.InfoWindow();
        markerInfoWin.setContent(content);
        marker.openInfoWindow(markerInfoWin, point); // 开启信息窗口
      }

      // 双击开启信息窗口
      // dblclick
      marker.addEventListener("click ", function () {
        let markerInfoWin = new T.InfoWindow();
        markerInfoWin.setContent(content);
        marker.openInfoWindow(markerInfoWin, point);
      });

      // 移入开启信息窗口
      // marker.addEventListener("mousedown ", function () {
      //   // let pCode = parentCode;
      //   // let id = markdata.children ? markdata.children[0].id : markdata.id;
      //   let markerInfoWin = new T.InfoWindow();
      //   markerInfoWin.setContent(content);
      //   marker.openInfoWindow(markerInfoWin, point);
      // });

      // 关闭信息窗口
      // marker.addEventListener("mouseup ", function () {
      //   let markerInfoWin = new T.InfoWindow();
      //   markerInfoWin.setContent(content);
      //   marker.closeInfoWindow(markerInfoWin, point);
      // });
    },
    loadText() {
      let T = window.T;
      if (this.mapdata.length != 0) {
        this.mapdata.forEach((item) => {
          let labelName = item.sName;
          if (item) {
            labelName = labelName.replace("GDLNG-", "");
          }
          let config = {
            text: labelName,
            offset: new T.Point(-45, -65),
            position: new T.LngLat(item.lng, item.lat)
          };
          let label = new T.Label(config);
          label.setFontColor("#fff");
          // label.setFontSize();
          label.setBackgroundColor("transparent");
          label.setBorderColor("transparent");
          // label.setAnchorPer([0.5, 0]); //偏移量
          // label.setBorderLine(0); //设置文本的边框线宽。
          // label.setFontColor("#fff"); //设置文本的边框线宽。
          // label.setOpacity(0); //设置文本的边框线宽。
          this.map.addOverLay(label);
        });
      }
    }
  }
});
</script>

<style lang="scss" scoped>
.xxdiv {
  //background-color: rgba($color: #000000, $alpha: 0.3);
  z-index: 899;
}

.tdt-infowindow-content-wrapper,
.tdt-infowindow-tip {
  //background: #535151 !important;
  border-radius: 20px !important;
}

::v-deep .tdt-infowindow-content-wrapper {
  font-family: Source Han Sans CN;
  font-weight: 500;
  font-size: 12px;
  color: #FFFFFF;
  background-color: transparent;
  background-image: url("../../../../public/mapimg/mapxx_bj.png");
  background-size: 100% 100%;
}
</style>
